//
//  ThingCollectionView.m
//  one·一个  tyw
//
//  Created by tyw on 15/9/9.
//  Copyright (c) 2015年 tyw. All rights reserved.
//

#import "ThingCollectionView.h"
#import "ThingCollectionViewCell.h"
#import "AFNetworking.h"
#import "DataService.h"
#import "ThingViewController.h"

@implementation ThingCollectionView


#pragma mark - init
- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout {
    if (self = [super initWithFrame:frame collectionViewLayout:layout]) {
        self.pagingEnabled = YES;
        self.showsHorizontalScrollIndicator = NO;
        self.backgroundColor = [UIColor clearColor];
        
        self.delegate = self;
        self.dataSource = self;
        self.pagingEnabled = YES;
        
        //注册
        [self registerClass:[ThingCollectionViewCell class] forCellWithReuseIdentifier:kThingCollectionViewCellId];
    }
    return self;
}

#pragma mark - collectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 9;
}

- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ThingCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:kThingCollectionViewCellId forIndexPath:indexPath];
    
    return cell;
}

//这个cell将要显示时调用
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    //只是为了菊花的显示
    UIResponder* responder = self.nextResponder;
    while (![responder isKindOfClass:[ThingViewController class]]) {
        responder = responder.nextResponder;
    }
    ThingViewController* thingVC = (ThingViewController*)responder;
    
    //01 获得数据，填充UI
    //--1 获得日期
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSDate* date = [NSDate date];
    NSString* dateStr = [formatter stringFromDate:date];
    
    
    //--2 构造参数params
    NSDictionary* params = @{@"strDate" : dateStr,
                             @"strRow" : @(indexPath.row+1),
                             };
    
    //--3 网络请求
    [DataService oneRequestUrl:kThingUrl httpMethod:@"GET" params:[params mutableCopy] block:^(id result) {
        if ([result isKindOfClass:[NSError class]]) {
            NSLog(@"东西页面数据获取失败  %@", result);
            [thingVC failHUD:@"网络错误 刷新失败"];
        }
        
        NSDictionary* dic = result[@"entTg"];
        ThingCollectionViewCell* newCell = (ThingCollectionViewCell*)cell;
        newCell.dataDic = dic;
        
        
        //02
        //配置参数    页面类型，首页0，文章1，问题2，东西3；时间日期
        NSMutableDictionary* info = [[NSMutableDictionary alloc] init];
        [info setObject:@3 forKey:@"strCt"];
        NSString* date = dic[@"strTm"];
        [info setObject:date forKey:@"date"];
        NSString* strId = dic[@"strId"];
        [info setObject:strId forKey:@"strId"];
        
        //读取本地数据,查看是否已点赞、已收藏
        BOOL liked = [Tools likedStrCt:@3 date:date];
        BOOL praised = [Tools praisedStrCt:@3 date:date];
        [info setObject:[NSNumber numberWithBool:liked] forKey:@"liked"];
        [info setObject:[NSNumber numberWithBool:praised] forKey:@"praised"];
        
        
        //03 发送通知
        //发送通知，某个cell已经显示，把这个cell的页面类型、日期、是否收藏、是否点赞  传递出去。（例如：首页、2015-9-20、已点赞、未收藏）
        //接收通知的  是ShareViewNight  和  ShareViewAA  刷新是否收藏按钮  ,  还有tableView ，刷新是否点赞按钮
        [[NSNotificationCenter defaultCenter] postNotificationName:kCollectionCellWillDisplayNotification object:nil userInfo:info];
    }];
    
    [thingVC completeHUD:@"刷新成功"];
}

#pragma mark - scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([scrollView isKindOfClass:[ThingCollectionView class]]) {
        
        //        NSLog(@"%f", scrollView.contentOffset.x);
        
        CGFloat offX = scrollView.contentOffset.x;
        
        //如果划过了50的距离,就刷新
        if (offX < -50) {
            UIResponder* responder = self.nextResponder;
            while (![responder isKindOfClass:[ThingViewController class]]) {
                responder = responder.nextResponder;
            }
            ThingViewController* thingVC = (ThingViewController*)responder;
            
            [thingVC showHUD:@"正在刷新数据"];
            [self performSelector:@selector(_reloadData) withObject:nil afterDelay:1];
        }
    }
}

- (void)_reloadData {
    [self reloadData];
}

@end
